<template>
  <div>
    <el-card shadow="never" class="card">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt=""/>
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  {{ t('workplace.toady') }}，20℃ - 32℃！
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never" class="card">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.shortcutOperation') }}</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col v-for="item in shortcut" :key="`team-${item.name}`" :span="8" class="mb-8px">
              <div class="flex items-center">
                <Icon :icon="item.icon" class="mr-8px" :style="{ color: item.color }"/>
                <el-link type="default" :underline="false" @click="handleShortcutClick(item)">
                  {{ item.name }}
                </el-link>
              </div>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>

      <el-card shadow="hover" class="mt-8px card">
        <template #header>
          <el-badge :value="bpmMyUnFinishTaskList?bpmMyUnFinishTaskList.length:0" :offset="[10, 5]" class="item">
            <span>流程待办</span>
          </el-badge>
          <div style=" float: right;">
            <el-input
              style="width: 100px"
              v-model="bpmQueryParams.name"
              placeholder="回车搜索"
              clearable
              @keyup.enter="getBpmMyUnFinishTask()"
            />
          </div>
        </template>

        <el-table v-if="bpmMyUnFinishTaskList&&bpmMyUnFinishTaskList.length>0"
                  show-overflow-tooltip
                  size="small"
                  style="width: 100%"
                  :max-height="400"
                  :data="bpmMyUnFinishTaskList">
          <el-table-column label="当前任务" prop="name" min-width="150"/>
          <el-table-column align="center" label="流程名称" prop="processInstance.name" width="180"/>
          <el-table-column
            label="发起人"
            prop="processInstance.startUser.nickname"
            width="60"
          />
          <el-table-column
            :formatter="dateFormatter"
            label="发起时间"
            prop="processInstance.createTime"
            width="180"
          />
          <el-table-column prop="userId_dictText" label="操作" width="60" fixed="right">
            <template #default="scope">
              <el-button type="text" @click="handleBpmAudit(scope.row)">处理</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-card>

      <el-card shadow="hover" class="mt-8px card">
        <template #header>

          <span>业务待办</span>
          <div style=" float: right;">
            <el-input
              style="width: 100px"
              v-model="workQueryParams.title"
              placeholder="回车搜索"
              clearable
              @keyup.enter="getUnFinishWorkflow"
            />
          </div>
        </template>
        <el-tabs v-model="taskActiveName" @tab-change="handleClick">
          <el-tab-pane v-if="taskFinishState=='未完成'" key="waitExecute" name="waitExecute">
            <template #label>
              <el-badge :value="unFinishFlow.waitExecuteNum" :offset="[10, 5]" class="item">
                <span><i class="el-icon-s-fold"></i> 待处理</span>
              </el-badge>
            </template>
          </el-tab-pane>
          <el-tab-pane key="create" name="create">
            <template #label>
              <el-badge :value="unFinishFlow.createNum" :offset="[10, 5]" class="item">
                <span><i class="el-icon-s-promotion"></i> 我发起的</span>
              </el-badge>
            </template>
          </el-tab-pane>
          <!--          <el-tab-pane key="assist" name="assist">-->
          <!--            <template #label>-->
          <!--              <el-badge :value="unFinishFlow.assistNum" :offset="[10, 0]" class="item">-->
          <!--                <span><i class="el-icon-s-promotion"></i> 我协助的</span>-->
          <!--              </el-badge>-->
          <!--            </template>-->
          <!--          </el-tab-pane>-->
        </el-tabs>
        <el-empty v-if="taskList.length<=0" :image-size="300"/>
        <el-table
          v-else
          :data="taskList"
          style="width: 100%"
          show-overflow-tooltip
          size="small"
          @row-dblclick="handleTask"
          :height="400"
        >
          <el-table-column prop="title" label="标题" min-width="150"/>
          <el-table-column prop="module" label="所属模块" width="80">
            <template #default="scope">
              <el-tag v-if="scope.row.module=='synergy'">部门协同</el-tag>
              <el-tag type="success" v-if="scope.row.module=='visual'">视觉工单</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="flowName" label="流程名称" width="100"/>
          <el-table-column v-if="taskActiveName=='waitExecute'" prop="creator_dictText"
                           label="发起人" width="60"/>
          <el-table-column v-if="taskActiveName=='create'" prop="userId_dictText" label="执行人"
                           width="60"/>
          <el-table-column prop="deadline" label="截止时间">
            <template #default="scope">
              {{ formatDate(scope.row.deadline) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发起时间">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="userId_dictText" label="操作" width="60" fixed="right">
            <template #default="scope">
              <el-button type="text" @click="handleTask(scope.row)">处理</el-button>
            </template>
          </el-table-column>


        </el-table>


      </el-card>
    </el-col>

    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">

      <el-card shadow="never" class="card">
        <el-empty :image-size="600"/>
      </el-card>

    </el-col>

  </el-row>


  <WorkTaskForm ref="workTaskFormRef" @success="getAllApi"/>
  <SubmitVisualOrder ref="submitVisualOrderRef" @success="getAllApi"/>
</template>
<script setup>

import {useUserStore} from '@/store/modules/user'
import router from "@/router";
import WorkTaskForm from "@/views/business/synergy/work/components/workTaskForm.vue";
import {WorkflowInfoApi} from "@/api/business/general/workflow/flow";
import {dateFormatter, formatDate} from '@/utils/formatTime'
import SubmitVisualOrder from "@/views/business/design/visual/model/SubmitVisualOrder.vue";
import {ref} from "vue";
import {VisualOrderApi} from '@/api/business/design/visual'
import {hasPermission} from "@/directives/permission/hasPermi";

//bpm 导入
import * as BpmTaskApi from '@/api/bpm/task'

const message = useMessage() // 消息弹窗

const {t} = useI18n()
const userStore = useUserStore()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const userId = userStore.getUser.id
const taskFinishState = ref('未完成')
const taskList = ref([])
const taskActiveName = ref('waitExecute')
const form = ref({})
const unFinishFlow = ref({})
const workQueryParams = ref({
  pageNo: 1,
  pageSize: 1000,
  creator: '',
  userId: '',
  title: '',
  module: '',
  state: 'going',
})
const workTaskFormRef = ref()
const submitVisualOrderRef = ref()

// 工作流未完成的数据
const bpmMyUnFinishTaskList = ref([])
const bpmQueryParams = ref({
  pageNo: 1,
  pageSize: 1000,
  name: '',
})

defineOptions({name: 'Index'})


//获取快捷入口
let shortcut = reactive < [] > ([])
const getShortcut = async () => {
  const data = [
    {
      name: '首页',
      icon: 'ion:home-outline',
      url: '/',
      color: '#1fdaca',
      key: 'index'
    },
    {
      name: '协同数据',
      icon: 'ep:promotion',
      url: 'synergy/work-list',
      color: '#1fdaca',
      key: 'synergyTask'
    },
    {
      name: '发起协同',
      icon: 'ep:plus',
      url: '',
      color: '#959dff',
      key: 'createSynergy'
    },
    {
      name: '设计工单',
      icon: 'ep:dessert',
      url: '/design/visual-order',
      color: '#ff6b6b',
      key: 'designWork'
    },
    // {
    //   name: 'AI 大模型',
    //   icon: 'tabler:ai',
    //   url: '/ai/chat',
    //   color: '#7c3aed'
    // },
    // {
    //   name: 'ERP 系统',
    //   icon: 'simple-icons:erpnext',
    //   url: '/erp/home',
    //   color: '#3fb27f'
    // },
    // {
    //   name: 'CRM 系统',
    //   icon: 'simple-icons:civicrm',
    //   url: '/crm/backlog',
    //   color: '#4daf1bc9'
    // },
    // {
    //   name: 'IoT 物联网',
    //   icon: 'fa-solid:hdd',
    //   url: '/iot/home',
    //   color: '#1a73e8'
    // }
  ]
  shortcut = Object.assign(shortcut, data)
}

const handleShortcutClick = (item) => {

  if (item.key == 'createSynergy') {
    workTaskFormRef.value.open()
  } else {
    router.push(item.url)
  }
}


const getUnFinishWorkflow = async () => {


  if (taskActiveName.value === 'create') {
    workQueryParams.value.userId = null
    workQueryParams.value.creator = userId
  } else if (taskActiveName.value === 'waitExecute') {
    workQueryParams.value.userId = userId
    workQueryParams.value.creator = null
  }
  let data = await WorkflowInfoApi.getWorkflowInfoPage(workQueryParams.value)
  taskList.value = data.list
  loading.value = false
}


const handleClick = (tab) => {
  taskActiveName.value = tab
  getUnFinishWorkflow()
}


/** 处理审批按钮 */
const handleBpmAudit = (row) => {
  router.push({
    name: 'BpmProcessInstanceDetail',
    query: {
      id: row.processInstance.id,
      taskId: row.id
    }
  })
}

const getAllApi = async () => {

  await Promise.all([
    getUnFinishWorkflow(),
    getShortcut(),
    getMyUnFinishFlow(),
    getBpmMyUnFinishTask()
  ])

}


const handleTask = async (flow) => {
  try {
    //如果是协同
    if (flow.module === 'synergy') {
      let id = flow.taskId
      router.push({name: 'SynergyWorkTask', params: {id}})
    } else if (flow.module === 'visual') {
      let data = await VisualOrderApi.getVisualOrderPage({id: flow.taskId})
      let row = data.list[0]
      if (flow.flowKey === 'going') {
        if (userId == row.takeUserId || hasPermission(['design:visual-order:admin'])) {
          submitVisualOrderRef.value.showVisible("submit", row)
        } else {
          message.error('您没有权限进行此操作');
        }
      } else if (flow.flowKey === 'audit') {
        if (userId == row.sendUserId || hasPermission(['design:visual-order:admin'])) {
          submitVisualOrderRef.value.showVisible("audit", row)
        } else {
          message.error('您没有权限进行此操作');
        }
      }
    }
  } finally {
    await getAllApi()
  }
}


const getMyUnFinishFlow = async () => {
  unFinishFlow.value = await WorkflowInfoApi.getMyUnFinishFlowNumber()

}

const getBpmMyUnFinishTask = async () => {
  const data = await BpmTaskApi.getTaskTodoPage(bpmQueryParams.value)
  bpmMyUnFinishTaskList.value = data.list
}


// 生命周期 - 挂载完成

onMounted
(() => {
  getAllApi()
})

// 待办任务处理

</script>


<style lang="scss" scoped>


.text-ellipsis {
  width: 180px;
  display: inline-block;
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出部分的文本 */
  text-overflow: ellipsis; /* 使用省略号代替超出部分的文本 */
}

.el-divider--horizontal {
  margin: 10px;
}

.box {
  width: 100%;
  height: 100%;
}

.tool-card {
  text-align: center;
  width: 100px;
  height: 80px;
  display: inline-block;
}

.tool-card :hover {
  background-color: #36a3f7;
  color: #ffffff
}

.card {
  border-radius: 15px; // 圆角优化
}
</style>
